package com.isczy.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.isczy.eduservice.entity.EduSubject;
import com.isczy.eduservice.entity.vo.ExcelSubjectVo;
import com.isczy.eduservice.service.EduSubjectService;
import com.isczy.servicebase.exceptionHandler.MyException;
import com.isczy.utils.ResultCode;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

/********************************************
 * @Brief:
 * @Version: 1.0
 * @Date: 2020年12月31日 10:50:50
 * @Author: ChangZiYang
 * ******************************************
 */
@NoArgsConstructor
@AllArgsConstructor
public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectVo> {

    private EduSubjectService eduSubjectService;

    @Override
    public void invoke(ExcelSubjectVo data, AnalysisContext context) {
        if(data == null) {
            throw MyException.builder()
                    .code(ResultCode.ERROR)
                    .message("没有读取到数据")
                    .build();
        }
        //添加一级分类
        EduSubject existOneSubject = this.existOneSubject(eduSubjectService,data.getOneSubjectName());
        if(existOneSubject == null) {
            //没有相同的
            existOneSubject = new EduSubject();
            existOneSubject.setTitle(data.getOneSubjectName());
            existOneSubject.setParentId("0");
            eduSubjectService.save(existOneSubject);
        }
        //获取一级分类id值
        String pid = existOneSubject.getId();
        //添加二级分类
        EduSubject existTwoSubject = this.existTwoSubject(eduSubjectService,data.getTwoSubjectName(), pid);
        if(existTwoSubject == null) {
            existTwoSubject = new EduSubject();
            existTwoSubject.setTitle(data.getTwoSubjectName());
            existTwoSubject.setParentId(pid);
            eduSubjectService.save(existTwoSubject);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    //判断一级分类不能重复添加
    private EduSubject existOneSubject(EduSubjectService subjectService,String name) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject oneSubject = subjectService.getOne(wrapper);
        return oneSubject;
    }

    //判断二级分类不能重复添加
    private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String pid) {
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject twoSubject = subjectService.getOne(wrapper);
        return twoSubject;
    }
}
